<?php

namespace App\Http\Controllers\Home;

use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\Users;
use App\Models\WordCategorys;
use App\Models\WordDownloadLogs;
use App\Models\Words;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WordController extends Controller
{
    /**
     * 文档分类页面
     * @param url home.word.wordCate
     * @param Request $request
     * @return bool
     */
    public function wordCate(){
        $title = '文档分类';
        return view('home.word.wordcate',compact('title'));
    }

    /**
     * 文档分类
     * @param url home.word.wordCatesApi
     * @param Request $request
     * @return bool
     * @return summary 简介
     * @return format 文件格式
     * @return $lists['word_hot']热门文档  $lists['word_new']最新文档
     */
    public function wordCatesApi(Request $request)
    {
        try{
            $lists = [];
            $lists['word_cate'] = WordCategorys::getCascaderList();
            foreach ($lists['word_cate'] as $key=>$val){
                $lists['word_cate'][$key]['bool'] = false;
            }
            $fields = ['id','thumb','title','cate_pid','cate_id','view','download','format'];
            $lists['word_hot'] = Words::allLists(['hot'=>2], $fields, null, 9, 'download');
            $lists['word_new'] = Words::allLists([], $fields, null, 9, 'created_at');
            foreach ($lists['word_hot'] as $key=>$val){
                $lists['word_hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['word_hot'][$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                $lists['word_hot'][$key]['cate_pid'] = WordCategorys::where('id',$val['cate_pid'])->value('name');
                $lists['word_hot'][$key]['cate_id'] = WordCategorys::where('id',$val['cate_id'])->value('name');
            }
            foreach ($lists['word_new'] as $key=>$val){
                $lists['word_new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['word_new'][$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                $lists['word_new'][$key]['cate_pid'] = WordCategorys::where('id',$val['cate_pid'])->value('name');
                $lists['word_new'][$key]['cate_id'] = WordCategorys::where('id',$val['cate_id'])->value('name');
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 文档列表页面
     * @param url home.word.wordList
     * @param Request $request
     * @return bool
     */
    public function wordList(){
        $title = '文档列表';
        return view('home.word.wordlist',compact('title'));
    }

    /**
     * 文档列表
     * @param url home.word.wordListsApi
     * @param Request $request
     * @param page 页码
     * @param keyword 热搜词条
     * @param cid 一级分类id
     * @param cid_id 二级分类id
     * @param sid 排序id 1:下载量 2:浏览量 不传或其他值：创建时间
     * @param orderby 'desc'倒叙 ‘asc'正序
     * @return bool
     * @return summary 简介
     * @return format 文件格式
     */
    public function wordListsApi(Request $request)
    {
        try{
            $map = [
                'keyword' => $request->get('keyword'),//热搜词条
                'cid' => $request->get('cid'),//一级分类id
                'cid_id' => $request->get('cid_id'),//二级分类id
            ];
            if (!empty($map['cid_id'])){
                $map['cid_id'] = explode(",", $map['cid_id']);
            }
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid');//排序
            $orderby = (string)$request->get('orderby','desc');//排序
            if ($sid == 1){
                $sort = 'download';
            }elseif ($sid == 2){
                $sort = 'view';
            }else{
                $sort = 'created_at';
            }
            $lists = [];
            $lists['cate'] = WordCategorys::getcates(['pid'=>0],['id','name','pid']);
            $fields = ['id','thumb','title','cate_pid','cate_id','view','download','format','size'];
            if(empty($map['cid'])){
                $cate_ids = WordCategorys::where('pid',0)->where('status','<>',-1)->orderBy('sort','asc')->pluck('id')->toArray();
                $field = " field(pid,".implode(',',$cate_ids)."),sort";
                $lists['children'] = WordCategorys::whereIn('pid',$cate_ids)->orderByRaw($field)->get(['id','name','pid'])->toArray();
//                $lists['children'] = WordCategorys::where('pid','<>','0')->where('status','<>',-1)->orderBy('sort','asc')->get(['id','name','pid']);
            }else{
                $lists['children'] = WordCategorys::getcates(['pid'=>$map['cid']],['id','name','pid']);
            }
            $lists['word'] = Words::allLists($map, $fields, $page, 9, $sort, $orderby);
            foreach ($lists['word'] as $key=>$val){
                $lists['word'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['word'][$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                $lists['word'][$key]['cate_pid'] = WordCategorys::where('id',$val['cate_pid'])->value('name');
                $lists['word'][$key]['cate_id'] = WordCategorys::where('id',$val['cate_id'])->value('name');
            }

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 文档详情页面
     * @param url home.word.wordDetails
     * @param Request $request
     * @return bool
     */
    public function wordDetails(){
        $title = '文档详情';
        return view('home.word.worddetails',compact('title'));
    }

    /**
     * 文档详情
     * @param url home.word.wordDetailsApi
     * @param Request $request
     * @param id 文档id
     * @return bool
     * @return show_link pdf文件供显示
     * @return file_link 原文件供下载
     * @return format 文件格式
     * @return size 文件大小
     * @return type 文件类型
     * @return is_collect 当前用户是否收藏：1未收藏，2已收藏
     * @return hot：热门文档  new：最新文档
     */
    public function wordDetailsApi(Request $request)
    {
        try{
            $id = (int)$request->get('id',1);//文档id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Words::details(['id'=>$id]);
            $cate_pid_name = WordCategorys::where('id',$lists['cate_pid'])->value('name');
            $cate_id_name = WordCategorys::where('id',$lists['cate_id'])->value('name');
            if (!empty($cate_id_name)){
                $lists['type'] = $cate_pid_name . '--' . $cate_id_name;
            }else{
                $lists['type'] = $cate_pid_name;
            }

            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            $lists['download'] = strlen($lists['download'])>=4 ? '999+' : $lists['download'];
            //是否收藏
            $lists['is_collect'] = 1;//默认未收藏
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            if (!empty($userinfo) && $userinfo['type'] == 1){
                if ($userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>1])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 1 : 2;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $userinfo['id'],
                    'foot_id' => $id,
                    'type'    => 5,
                ];
                $foot_id = Footprints::where($foot_arr)->value('id');
                if($foot_id > 0){
                    Footprints::where($foot_arr)->update(['updated_at'=>date('Y-m-d H:i:s')]);
                }else{
                    Footprints::create($foot_arr);
                }
            }
            $lists['hot'] = Words::allLists(['hot'=>2], ['id','title','download'], null, 10, 'download');
            $lists['new'] = Words::allLists([], ['id','title','download'], null, 10, 'created_at');

            Words::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }

        return view('home.word.wordcate',compact('lists','word'));
    }

    /**
     * 文档下载
     * @param url home.word.wordDownloadApi
     * @param Request $request
     * @param word_id 文档id
     * @return bool
     */
    public function wordDownloadApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return $this->writeJson(1,null,'用户不存在,请联系客服!');
            }else{
                if($userinfo['status'] == 2){
                    return $this->writeJson(1, null,'账户正在审核中，请等待审核!');
                }elseif($userinfo['status'] == 3){
                    return $this->writeJson(1, null,'账号未通过审核，请前往个人中心查看原因并重新提交审核!');
                }elseif ($userinfo['status'] == 4){
                    return $this->writeJson(1, null,'账号已锁定，请前往个人中心查看原因或联系客服!');
                }
                if($userinfo['type'] != 1)  return $this->writeJson(1,null,'供应商不能下载文档!');
            }

            $word_id = (int)$request->post('word_id');
            if (empty($word_id)) return $this->writeJson(1,null,'参数错误');
            $params = [
                'word_id' => $word_id,
                'user_id' => $user_id,
            ];
            WordDownloadLogs::create($params);
            Words::where('id',$word_id)->increment('download');//下载量加1
            $link = Words::where('id',$word_id)->value('file_link');
            return $this->writeJson(0, $link, '下载成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 文档收藏
     * @param url home.word.wordCollectApi
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function wordCollectApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return $this->writeJson(1,null,'用户不存在,请联系客服!');
            }else{
                if($userinfo['status'] == 2){
                    return $this->writeJson(1, null,'账户正在审核中，请等待审核!');
                }elseif($userinfo['status'] == 3){
                    return $this->writeJson(1, null,'账号未通过审核，请前往个人中心查看原因并重新提交审核!');
                }elseif ($userinfo['status'] == 4){
                    return $this->writeJson(1, null,'账号已锁定，请前往个人中心查看原因或联系客服!');
                }
                if($userinfo['type'] != 1)  return $this->writeJson(1,null,'供应商不能收藏文档!');
            }

            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>1])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 1,
                ];
                Collections::create($params);
                Words::where('id',$collect_id)->increment('collect');//收藏量加1
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>1])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


}